Puzzle 2 Explanation: Map Type
Understand why you can get nil as your output.
We'll cover the following
Try it yourself#
Try executing the code below to see the result for yourself.
Explanation#
The zero value for an uninitialized map is nil. Some operations on Go’s map
type is nil safe, meaning they will work with a nil map without panicking.
Both len and accessing a value (for example, m["Hello"]) will work on a nil map. The len function returns 0 and access to a value with a key that does the following:
- If the key is on the map, return its value.
- If the key is not on the map, return the zero value for the value type.
In this example, the key “Hello” is not found on the map and you’ll get back
the zero value for int, which is 0.
That’s a practical thing to do. If you want to count items (say, word frequency in
a document), you can do m[word]++ without worrying if the word is in the map m
or not.
This leads to a question: How do we know if the value we got from a map is there or if it’s the zero value of value type? The answer is to use the comma (,ok) paradigm.
When we type val, ok := m[key], ok will be true if we got the value from the map and false if the key is not in the map.
There are other nil safe types in Go. For example, we can ask the length of a nil slice, receive a value from an empty channel (though we’ll be blocked forever), and more.
Puzzle 2: Empty-handed
Puzzle 3: When in Kraków